import useUserStore from '@/store/modules/user'

import { getTodoMessageList } from '@/api/businessSettings/agent'
const userStore = useUserStore()
const path = import.meta.env.VITE_APP_URL
const userID = userStore.userInfo.userId
const url = (path + '/system/websocket/' + userID).replace(/http|https/, 'ws')
let socket,
  maxRetries = 1000, // 最大重试次数
  currentRetry = 0 // 当前重试次数
const retryInterval = 3000 // 重连间隔（毫秒）

const limitTime = 3000 // 限制间隔时间内消息
const limitShowList = 3 // 限制显示条数
const hiddenTime = 5000 // 消息消失时间
let receivingTime = 0, //接收时间
  continueAdd = true, // 是否继续添加
  isFirst = true
// 当前接收时间
function connectSocket() {
  socket = new WebSocket(url)
  socket.onmessage = function (event) {
    if (isFirst) {
      isFirst = false
      return
    }
    const data = JSON.parse(event.data)
    const nowTime = new Date().getTime()
    if (nowTime - receivingTime > 3000) {
      receivingTime = 0
      continueAdd = true
    }
    if (receivingTime === 0) {
      receivingTime = nowTime
    }
    // 更新未读消息
    data.total && userStore.updateMsgNumber(data.total || 0)
    // 推送消息
    if (
      userStore.todoList.length < limitShowList &&
      nowTime - receivingTime < limitTime &&
      continueAdd
    ) {
      if (data.newtodo) {
        userStore.updateTodoList([
          ...userStore.todoList,
          { msg: data.newtodo, timeStamp: nowTime }
        ])

        if (userStore.todoList.length === 3) {
          continueAdd = false
        }
      }
    }
    deleteList()
  }
  socket.onopen = function (event) {
    console.log('WebSocket is open now.')
    currentRetry = 0
  }
  socket.onerror = function (event) {
    if (!isFirst) {
      isFirst = true
    }
    socket.close()
  }
  socket.onclose = function (event) {
    if (currentRetry < maxRetries) {
      setTimeout(connectSocket, retryInterval)
      console.log('WebSocket reconnect')
      currentRetry++
    }
  }
}

// 删除list
function deleteList() {
  let timer
  if (userStore.todoList.length) {
    timer = setTimeout(() => {
      const filter = userStore.todoList.filter(v => {
        return v.timeStamp + 4500 > new Date().getTime()
      })
      userStore.updateTodoList(filter)
      deleteList()
    }, hiddenTime)
  } else {
    clearTimeout(timer)
  }
}

// 获取未读消息数量
function getTotal() {
  getTodoMessageList({ readFlag: 'N', pageNum: 1, pageSize: 10 }).then(res => {
    userStore.updateMsgNumber(res.total)
  })
}

const onbeforeunload = function () {
  ws.close()
}
window.addEventListener('beforeunload', onbeforeunload)
getTotal()
connectSocket()

export default socket
